package http;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

public class CaptchaForm {
	public static int GET = 1;
	public static int POST = 2;
	private Link action;
	private Map<String,String> parameter = new LinkedHashMap<String,String>();
	private int method = 2;
	public int getMethod() {
		return method;
	}
	private String captchaParameter = null;
	public void setAction(Link action) {
		this.action = action;
	}
	public void setMethod(int method) {
		this.method = method;
	}
	public void addParameter(String key,String value) {
		this.parameter.put(key, value);
	}
	public void addParameter(String key) {
		this.parameter.put(key, null);
	}
	public void setParameter(String key,String value) {
		if (this.parameter.containsKey(key))
			this.parameter.put(key, value);
	}
	public void setCaptchaParameter(String key) {
		if (this.parameter.containsKey(key))
			captchaParameter = key;
	}
	public void solveCaptcha(String value) {
		if (captchaParameter != null)
			this.parameter.put(captchaParameter, value);
	}
	public String getPostMessage() {
		String postMsg = "";
		for (Entry<String,String> param:parameter.entrySet()) {
			try {
				postMsg = postMsg.concat(URLEncoder.encode(param.getKey(), "UTF-8").concat("=").concat(URLEncoder.encode(param.getValue(), "UTF-8")).concat("&"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		if (postMsg.charAt(postMsg.length()-1) == '&')
			postMsg = postMsg.substring(0, postMsg.length()-1);
		return postMsg;
	}
	public String toString() {
		String formCall = action.toString();
		if (method == GET) {
			if (parameter.size() > 0)
				formCall = formCall.concat("?");
			formCall = formCall.concat(getPostMessage());
		}
		return formCall;
	}
}
